package com.a01_2021.thousandstimes.general.service.impl;

import com.a01_2021.thousandstimes.exception.CustomException;
import com.a01_2021.thousandstimes.exception.CustomExceptionType;
import com.a01_2021.thousandstimes.general.entity.PersonnelInfomation;
import com.a01_2021.thousandstimes.general.entity.SysUser;
import com.a01_2021.thousandstimes.general.mapper.SysUserMapper;
import com.a01_2021.thousandstimes.general.service.PersonnelInfomationService;
import com.a01_2021.thousandstimes.saas.entity.vo.InforQuery;
import com.a01_2021.thousandstimes.saas.mapper.PersonnelInfomationMapper;
import com.a01_2021.thousandstimes.utils.AjaxResponse;
import com.a01_2021.thousandstimes.utils.Desensitization;
import com.a01_2021.thousandstimes.utils.IO;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author FRQ
 * @since 2021-02-22
 */
@Service
public class PersonnelInfomationServiceImpl extends ServiceImpl<PersonnelInfomationMapper, PersonnelInfomation> implements PersonnelInfomationService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PersonnelInfomationMapper personnelInfomationMapper;

    static List<String> expectExt = new ArrayList<>();//限制上传文件后缀名

    static {
        expectExt.add(".jpg");
        expectExt.add(".png");
        expectExt.add(".doc");
        expectExt.add(".docx");
    }

    @Value("${path.personnelInformationFolder}")
    private String personnelInformationFolder;

    @Override
    @DS("#header.instanceid")
    public AjaxResponse insertInfo(InforQuery inforQuery) {

        if (inforQuery.getName() == null || inforQuery.getUsername() == null) {
            return AjaxResponse.error("姓名和用户名不能为空");
        } else {
            //调用usersMapper方法，根据用户名查询用户ID
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            // where username=?
            wrapper.eq("username", inforQuery.getUsername());
            SysUser users = sysUserMapper.selectOne(wrapper);
            PersonnelInfomation personnelInfomation = new PersonnelInfomation();
            //保存用户ID
            personnelInfomation.setName(inforQuery.getName());
            personnelInfomation.setPersonalId(inforQuery.getPersonalId());
            personnelInfomation.setGender(inforQuery.getGender());
            personnelInfomation.setUserId(users.getId());
            //保存个人信息
            personnelInfomationMapper.insert(personnelInfomation);
            return AjaxResponse.success();
        }
    }

    /**
     * 上传简历
     *
     * @param instanceId 实例id
     * @param userId     用户id
     * @param file       上传文件
     * @return HashMap
     * @throws CustomException 当文件后缀名不符合要求时抛出
     * @throws IOException     IO异常
     */
    @Override
    public HashMap<String, String> uploadResume(String instanceId, long userId, MultipartFile file) throws CustomException, IOException {
        //查询对应人事信息
        QueryWrapper<PersonnelInfomation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        PersonnelInfomation personnelInfomation = personnelInfomationMapper.selectOne(queryWrapper);
        if (personnelInfomation == null) {
            //人事信息不存在
            throw new CustomException(CustomExceptionType.PERSONNEL_INFORMATION_NOT_FOUND_ERROR, "找不到该用户对应的人事信息");
        }
        //校验文件后缀名并存储
        String ext = IO.getExt(file, expectExt);
        String url = IO.saveFile(file, ext, "/" + personnelInformationFolder + "/" + instanceId);
        //将文件URL添加到数据库中
        personnelInfomation.setResume("/resume/" + instanceId + "/" + url);
        personnelInfomationMapper.updateById(personnelInfomation);
        //构造返回信息
        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("userId", String.valueOf(userId));
        resultMap.put("resume", personnelInfomation.getResume());
        return resultMap;
    }

    /**
     * 更新个人信息
     *
     * @param personnelInfomation 个人信息实体类
     * @return 个人信息实体类
     * @throws CustomException 当个人信息条目不存在,修改他人个人信息时抛出该异常
     */
    @Override
    public PersonnelInfomation updateInfo(long userId, PersonnelInfomation personnelInfomation) throws CustomException {
        PersonnelInfomation resultItem = personnelInfomationMapper.selectById(personnelInfomation.getId());
        if (resultItem == null) {
            throw new CustomException(CustomExceptionType.PERSONNEL_INFORMATION_NOT_FOUND_ERROR, "找不到对应个人信息");
        }
        if (resultItem.getUserId() != userId) {
            throw new CustomException(CustomExceptionType.OPERATION_NOT_ALLOW, "非法操作");
        }
        //将传入的修改变量置入数据库
        if (!StringUtils.isEmpty(personnelInfomation.getName())) {
            resultItem.setPersonalId(personnelInfomation.getName());
        }
        if (!StringUtils.isEmpty(personnelInfomation.getGender())) {
            resultItem.setGender(personnelInfomation.getGender());
        }
        if (!StringUtils.isEmpty(personnelInfomation.getBirthday())) {
            resultItem.setBirthday(personnelInfomation.getBirthday());
        }
        if (!StringUtils.isEmpty(personnelInfomation.getWechat())) {
            resultItem.setWechat(personnelInfomation.getWechat());
        }
        if (!StringUtils.isEmpty(personnelInfomation.getQq())) {
            resultItem.setQq(personnelInfomation.getQq());
        }
        personnelInfomationMapper.updateById(resultItem);
        return resultItem;
    }

    /**
     * 通过用户id获取名字
     *
     * @param userId 用户id
     * @return 返还用户名字
     */
    @Override
    public String getName(long userId) throws CustomException {
        QueryWrapper<PersonnelInfomation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        PersonnelInfomation personnelInfomation = personnelInfomationMapper.selectOne(queryWrapper);
        if (personnelInfomation == null) {
            return null;
        }
        return personnelInfomation.getName();
    }

    /**
     * 通过用户id获取个人信息
     *
     * @param userId 用户id
     * @return PersonalInformation
     */
    @Override
    public PersonnelInfomation getByUserId(long userId) {
        QueryWrapper<PersonnelInfomation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        PersonnelInfomation personnelInfomation = personnelInfomationMapper.selectOne(queryWrapper);
        //脱敏身份证号
        personnelInfomation.setPersonalId(Desensitization.personalNo(personnelInfomation.getPersonalId()));
        return personnelInfomation;
    }

    /**
     * 通过用户id获取个人信息（不脱敏
     *
     * @param userId 用户id
     * @return PersonalInformation
     */
    @Override
    public PersonnelInfomation getByUserIdOriginal(long userId) {
        QueryWrapper<PersonnelInfomation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return personnelInfomationMapper.selectOne(queryWrapper);
    }

    /**
     * 通过用户类与个人信息类更新主数据库信息，若不存在则置入主数据库
     *
     * @param personnelInfomation 个人信息类
     * @param sysUser             用户类
     * @return 主数据库用户id
     */
    @DS("master")
    @Override
    public long updatePersonalInformationToMaster(PersonnelInfomation personnelInfomation, SysUser sysUser) {
        QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", sysUser.getUsername());
        SysUser mUser = sysUserMapper.selectOne(userQueryWrapper);//获取主数据库的用户
        if (mUser == null) {
            //主数据库中无此用户
            mUser = new SysUser(null, sysUser.getUsername(), sysUser.getPassword(), sysUser.getHeadPic(), 0);
            sysUserMapper.insert(mUser);
        }
        QueryWrapper<PersonnelInfomation> personnelInfomationQueryWrapper = new QueryWrapper<>();
        personnelInfomationQueryWrapper.eq("personal_id", personnelInfomation.getPersonalId());
        PersonnelInfomation mPersonnelInformation = personnelInfomationMapper.selectOne(personnelInfomationQueryWrapper);//获取主数据库的个人信息
        if (mPersonnelInformation == null) {
            //主数据库中无此个人信息
            mPersonnelInformation = new PersonnelInfomation(
                    null,
                    mUser.getId(),//设置用户主数据库中的id
                    personnelInfomation.getName(),
                    personnelInfomation.getPersonalId(),
                    personnelInfomation.getGender(),
                    personnelInfomation.getBirthday(),
                    personnelInfomation.getWechat(),
                    personnelInfomation.getQq(),
                    personnelInfomation.getResume());
            personnelInfomationMapper.insert(mPersonnelInformation);
        } else {
            //主数据库中有此个人信息，更新个人信息
            mPersonnelInformation
                    .setId(mUser.getId())
                    .setName(personnelInfomation.getName())
                    .setPersonalId(personnelInfomation.getPersonalId())
                    .setGender(personnelInfomation.getGender())
                    .setBirthday(personnelInfomation.getBirthday())
                    .setWechat(personnelInfomation.getWechat())
                    .setQq(personnelInfomation.getQq())
                    .setResume(personnelInfomation.getResume());
            personnelInfomationMapper.updateById(mPersonnelInformation);
        }
        return mUser.getId();
    }
}
